﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YaAppoint.Common;
using YaAppoint.Devices;
using YaAppoint.Response;

namespace YaAppoint.CustomSettings
{
    /// <summary>
    /// 科室设备类型设置服务
    /// </summary>
    [RemoteService(isEnabled: false)]
    public class CustomSettingAppService(ICommonAppService commonService,
                                         IConfiguration configuration,
                                         IRepository<Department,Guid> depRepository,
                                         IRepository<Device,Guid> deviceRepository,
                                         IRepository<DeviceType,Guid> deviceTypeRepository,
                                         AsyncQueryableExecuter queryableExecuter,
                                         IRepository<CustomSetting,Guid> customSettingRepostitory,
                                         IMapper mapper) : ApplicationService,ICustomSettingAppService,ITransientDependency
    {
        private readonly ICommonAppService _commonAppService = commonService;
        private readonly IRepository<CustomSetting, Guid> _customSettingRepostitory = customSettingRepostitory;
        private readonly IMapper _mapper = mapper;
        private readonly AsyncQueryableExecuter _queryableExecuter = queryableExecuter;
        private readonly IConfiguration _configration = configuration;
        private readonly IRepository<Department, Guid> _depRepository = depRepository;
        private readonly IRepository<Device, Guid> _deviceRepository = deviceRepository;
        private readonly IRepository<DeviceType, Guid> _deviceTypeRepository = deviceTypeRepository;


        /// <summary>
        ///  获取到诊模式选项
        /// </summary>
        public BackJson GetCheckInModeOptions()
        {
            var values = Enum.GetValues(typeof(CheckInMode));
            List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
            foreach (Enum item in values)
            {
                data.Add(new Dictionary<string, object> {
                    { "value",Convert.ToInt32(item)},
                    { "label",_commonAppService.GetEnumValueDescription(item)}
                });
            }
            return new BackJson
            {
                code = 0,
                data = data
            };
        }

        public BackJson GetHisIntervalSpanOptions()
        {
            var values = Enum.GetValues(typeof(HisIntervalSpan));
            List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
            foreach (Enum item in values)
            {
                data.Add(new Dictionary<string, object> {
                    {"value",Convert.ToInt32(item)},
                    {"label",_commonAppService.GetEnumValueDescription(item)}
                });
            }
            return new BackJson()
            {
                code = 0,
                data = data
            };
        }

        /// <summary>
        /// 获取设置
        /// </summary>
        public async Task<BackJson> GetSetting(SettingLevel level,Guid? depId,Guid? deviceTypeId,Guid? deviceId)
        {
            var query = await _customSettingRepostitory.GetQueryableAsync();
            switch (level)
            {
                case SettingLevel.Department:
                    query = query.Where(s =>s.Level==level && s.DepartmentId == depId && s.DeviceTypeId == null && s.DeviceId == null);
                    break;

                case SettingLevel.DeviceType:
                    query = query.Where(s =>s.Level==level && s.DepartmentId == depId && s.DeviceTypeId == deviceTypeId && s.DeviceId == null);
                    break;

                case SettingLevel.Device:
                    query = query.Where(s=>s.Level==level && s.DepartmentId==depId && s.DeviceTypeId ==deviceTypeId && s.DeviceId==deviceId);
                    break;

                case SettingLevel.Global:
                    query = query.Where(s => s.Level == level && s.DepartmentId ==null && s.DeviceTypeId==null && s.DeviceId==null);
                    break;

                default:
                    throw new BusinessException(CustomErrorCodes.GetCustomSettingParamError);
            }

            CustomSetting setting = null;

            var settingList = await _queryableExecuter.ToListAsync(query);
            if (settingList == null || settingList.Count == 0)
            {
                if (level == SettingLevel.Global)
                {
                    throw new BusinessException(CustomErrorCodes.NoCustomSettingFound); 
                }
                else
                {
                    CustomSetting newSetting = new CustomSetting();
                    newSetting.Level = level;
                    newSetting.DepartmentId = depId;
                    newSetting.DeviceTypeId = deviceTypeId;
                    newSetting.DeviceId = deviceId;
                    newSetting.AppointableCount = null;
                    newSetting.AutoAppointableCount = null;
                    newSetting.CheckInMode = null;
                    newSetting.Earliest = null;
                    newSetting.LatestAppoint = null;
                    newSetting.UnpaidWillBeCancel = null;
                    newSetting.UnpaidTimeLimit = null;
                    await _customSettingRepostitory.InsertAsync(newSetting);
                    setting = newSetting;
                }
            }
            else if (settingList != null && settingList.Count > 1)
            {
                throw new BusinessException(CustomErrorCodes.FoundMoreThanOneSettings);
            }
            else if(settingList!=null && settingList.Count==1)
            {
                setting = settingList[0];
            }
                return new BackJson()
                {
                    code = 0,
                    data = _mapper.Map<CustomSetting, CustomSettingDto>(setting!)
                };
        }

       

        /// <summary>
        /// 保存设置
        /// </summary>
        public async Task<BackJson> Save(CustomSettingDto dto)
        {
            var setting = await _customSettingRepostitory.FirstOrDefaultAsync(s => s.Id == dto.Id);
            if (setting == null)
            {
                throw new BusinessException(CustomErrorCodes.NoCustomSettingFound);
            }
            _mapper.Map<CustomSettingDto, CustomSetting>(dto, setting);
            await _customSettingRepostitory.UpdateAsync(setting);
            return new BackJson()
            {
                code=0,
                msg ="保存成功。"
            };
        }


        /// <summary>
        /// 获取左侧栏树形数据
        /// </summary>
        public async Task<BackJson> GetLeftTreeData(Guid? depId)
        {
            var query = await _depRepository.GetQueryableAsync();

            var hospital = new Dictionary<string, object>();
            hospital.Add("name", _configration!["InstitutionName"]!);
            hospital.Add("id", 1);
            hospital.Add("level", "hospital");
            hospital.Add("icon", "fa fa-hospital");

            if (depId != null)
            {
                query = query.Where(x => x.Id == depId);
            }
            var depList = await _queryableExecuter.ToListAsync(query);
            if (depList!=null && depList.Count > 0)
            {
                var hospitalChildren = new List<Dictionary<string, object>>();
                foreach (var dep in depList)
                {
                    var department = new Dictionary<string, object>();
                    department.Add("name", dep.Name);
                    department.Add("id",dep.Id);
                    department.Add("level", "department");
                    department.Add("icon", "fa fa-building");

                    var deviceTypeList = dep.DeviceTypes;
                    if (deviceTypeList != null && deviceTypeList.Count > 0)
                    {
                        var departmentChildren = new List<Dictionary<string, object>>();
                        foreach (var deviceType in deviceTypeList)
                        {
                            var dt = new Dictionary<string, object>();
                            dt.Add("name", deviceType.Name);
                            dt.Add("id", deviceType.Id);
                            dt.Add("level","deviceType");
                            dt.Add("icon", "fa fa-list");

                            var deviceList = await _deviceRepository.GetListAsync(d=>d.DepartmentId==dep.Id && d.DeviceTypeId == deviceType.Id);
                            if (deviceList != null && deviceList.Count > 0)
                            {
                                var deviceTypeChildren = new List<Dictionary<string, object>>();
                                foreach (var device in deviceList)
                                {
                                    var de = new Dictionary<string, object>();
                                    de.Add("name", device.Name);
                                    de.Add("id", device.Id);
                                    de.Add("level","device");
                                    de.Add("icon", "fa fa-tachograph-digital");
                                    deviceTypeChildren.Add(de);
                                }
                                dt.Add("children", deviceTypeChildren);
                            }
                            departmentChildren.Add(dt);
                        }
                        department.Add("children", departmentChildren);
                    }
                    hospitalChildren.Add(department);
                }
                hospital.Add("children", hospitalChildren);
            }

            var data = new List<Dictionary<string, object>>();
            data.Add(hospital);
            
            return new BackJson()
            {
                code=0,
                data= data
            };
        }

        /// <summary>
        /// 获取设备自定义设置
        /// </summary>
        public async Task<CustomSettingDto> GetDeviceSetting(Guid deviceId)
        {
            var device = await _deviceRepository.FirstOrDefaultAsync(d=>d.Id==deviceId);
            if (device == null)
            {
                throw new BusinessException(CustomErrorCodes.DeviceNotExist);
            }
            var department = await _depRepository.FirstOrDefaultAsync(d=>d.Id==device.DepartmentId);
            var deviceType =device.DeviceType;

            // 获取全局设置
            var globalSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s=>s.Level==SettingLevel.Global);
            if (globalSetting == null)
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingNotFound);
            }

            // 获取科室设置
            var depSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s=>s.Level== SettingLevel.Department
                                                                                    && s.DepartmentId== department.Id
                                                                                    && s.DeviceTypeId==null 
                                                                                    && s.DeviceId ==null);
            if (depSetting == null)
            {
                depSetting = globalSetting;
            }

            // 获取设备类型设置
            var deviceTypeSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s=>s.Level==SettingLevel.DeviceType
                                                                                           && s.DepartmentId==department.Id
                                                                                           && s.DeviceTypeId == deviceType.Id
                                                                                           && s.DeviceId==null);
            if (deviceTypeSetting == null)
            {
                deviceTypeSetting = depSetting;
            }


            // 获取设备设置
            var deviceSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s=>s.Level==SettingLevel.Device
                                                                                       && s.DepartmentId==department.Id
                                                                                       && s.DeviceTypeId==deviceType.Id
                                                                                       && s.DeviceId== deviceId);
            if (deviceSetting == null)
            {
                deviceSetting = depSetting;
            }

            var setting = new CustomSettingDto();
            setting.Id = null;


            #region AppointableCount （可预约天数） 
            if (deviceSetting.AppointableCount != null)
            {
                setting.AppointableCount = deviceSetting.AppointableCount;
            }
            else if (deviceTypeSetting.AppointableCount != null)
            {
                setting.AppointableCount = deviceTypeSetting.AppointableCount;
            }
            else if (depSetting.AppointableCount != null)
            {
                setting.AppointableCount = depSetting.AppointableCount;
            }
            else if (globalSetting.AppointableCount != null)
            { 
                setting.AppointableCount = globalSetting.AppointableCount;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","AppointableCount(可预约天数)"}
                    }
                };
            }
            #endregion

            #region (自动预约可预约天数)
            if (deviceTypeSetting.AutoAppointableCount != null)
            {
                setting.AutoAppointableCount = deviceTypeSetting.AutoAppointableCount;
            }
            else if (depSetting.AutoAppointableCount != null)
            {
                setting.AutoAppointableCount = depSetting.AutoAppointableCount;
            }
            else if (globalSetting.AppointableCount != null)
            {
                setting.AutoAppointableCount = globalSetting.AutoAppointableCount;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","AutoAppointableCount(自动预约天数)"}
                    }
                };
            }
            #endregion

            #region Earliest (可提前签到分钟数)
            if (deviceSetting.Earliest != null)
            {
                setting.Earliest = deviceSetting.Earliest;
            }
            else if (deviceTypeSetting.Earliest != null)
            {
                setting.Earliest = deviceTypeSetting.Earliest;
            }
            else if (depSetting.Earliest != null)
            {
                setting.Earliest = depSetting.Earliest;
            }
            else if (globalSetting.Earliest != null)
            {
                setting.Earliest = globalSetting.Earliest;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","Earliest(可提前签到分钟数)"}
                    }
                };
            }
            #endregion

            #region CheckInMode (签到模式)
            if (deviceSetting.CheckInMode != null)
            {
                setting.CheckInMode = deviceSetting.CheckInMode;
            }
            else if (deviceTypeSetting.CheckInMode != null)
            {
                setting.CheckInMode = deviceTypeSetting.CheckInMode;
            }
            else if (depSetting.CheckInMode != null)
            {
                setting.CheckInMode = depSetting.CheckInMode;
            }
            else if (globalSetting.CheckInMode != null)
            { 
                setting.CheckInMode = globalSetting.CheckInMode;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","CheckInMode(签到模式)"}
                    }
                };
            }
            #endregion

            #region LatestAppoint (最迟提前预约时间)
            if (deviceSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = deviceSetting.LatestAppoint;
            }
            else if (deviceTypeSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = deviceTypeSetting.LatestAppoint;
            }
            else if (depSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = depSetting.LatestAppoint;
            }
            else if (globalSetting.LatestAppoint != null)
            { 
                setting.LatestAppoint = globalSetting.LatestAppoint;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","LatestAppoint(最迟提前预约时间)"}
                    }
                };
            }
            #endregion

            #region UnpaidWillBeCancel （未支付预约自动取消）
            if (deviceSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = deviceSetting.UnpaidWillBeCancel;
            }
            else if (deviceTypeSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = deviceTypeSetting.UnpaidWillBeCancel;
            }
            else if (depSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = depSetting.UnpaidWillBeCancel;
            }
            else if (globalSetting.UnpaidWillBeCancel != null)
            { 
                setting.UnpaidWillBeCancel = globalSetting.UnpaidWillBeCancel;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","UnpaidWillBeCancel(是否自动取消未支付预约)"}
                    }
                };
            }
            #endregion

            #region UnpaidTimeLimit (取消未支付预约时间)
            if (deviceSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = deviceSetting.UnpaidTimeLimit;
            }
            else if (deviceTypeSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = deviceTypeSetting.UnpaidTimeLimit;
            }
            else if (depSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = depSetting.UnpaidTimeLimit;
            }
            else if (globalSetting.UnpaidTimeLimit != null)
            { 
                setting.UnpaidTimeLimit= globalSetting.UnpaidTimeLimit;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","UnpaidTimeLimit(是否自动取消未支付预约)"}
                    }
                };
            }
            #endregion

            return setting;
        }

        /// <summary>
        /// 获取多科室下所有设备的自定义设置
        /// </summary>
        /// <param name="depCodeList"></param>
        /// <returns></returns>


        /// <summary>
        /// 批量获取设备设置
        /// </summary>
        public async Task<List<CustomSettingDto>> GetDeviceSettingList(List<DeviceDto> devices)
        {
            List<CustomSettingDto> deviceSettingList = new List<CustomSettingDto>();
            if (devices.Count > 0)
            {
                var depIdList = devices.Select(d => d.DepartmentId).ToList();
                var deviceIds = devices.Select(d => d.Id).ToList();
                var deviceTypeId = devices[0].DeviceTypeId;

                var query = await _customSettingRepostitory.GetQueryableAsync();
                query = query.Where(s => s.Level == SettingLevel.Global
                                         || (s.Level == SettingLevel.Department   && depIdList.Contains(s.DepartmentId!.Value))
                                         || (s.Level ==SettingLevel.DeviceType  && s.DeviceTypeId!.Value ==deviceTypeId)
                                         || (s.Level==SettingLevel.Device && deviceIds.Contains(s.DeviceId!.Value))
                                   );
                var settingList =_mapper.Map<List<CustomSetting>,List<CustomSettingDto>>( await _queryableExecuter.ToListAsync(query));
                foreach (var device in devices)
                {
                    var deviceSetting = settingList.FirstOrDefault(s => s.Level == SettingLevel.Device
                                                                && s.DepartmentId == device.DepartmentId 
                                                                && s.DeviceTypeId == device.DeviceTypeId
                                                                && s.DeviceId == device.Id
                                                             );
                    if (deviceSetting == null)
                    {
                        Logger.LogError($"his预约页面，获取推荐号池，其中设备{device.Id!.Value.ToString()}的是指不批量获取设置的集合中");
                        continue;
                    }
                    var golbalSetting = settingList.FirstOrDefault(s=>s.Level==SettingLevel.Global);
                    if (golbalSetting == null)
                    {
                        Logger.LogError($"his预约页面，获取推荐号池，其中全局设置未在批量获取设置中获取到");
                        continue;
                    }
                    var depSetting = settingList.FirstOrDefault(s => s.Level == SettingLevel.Department
                                                                    && s.DepartmentId != null 
                                                                    && s.DepartmentId!.Value == device.DepartmentId);
                    if (depSetting == null)
                    {
                        Logger.LogError($"his预约页面，获取推荐号池，其中设备:{device.Id}的科室：{device.DepartmentId}的设置未在批量设置中获取到");
                        continue;
                    }

                    var depDeviceTypeSetting = settingList.FirstOrDefault(s => s.Level == SettingLevel.DeviceType
                                                                            && s.DepartmentId != null
                                                                            && s.DepartmentId.Value == device.DepartmentId
                                                                            && s.DeviceTypeId != null
                                                                            && s.DeviceTypeId.Value == device.DeviceTypeId
                                                                          );
                    if (depDeviceTypeSetting == null)
                    {
                        Logger.LogError($"his预约页面。获取推荐号池，其中设备({device.Id})的科室({device.DepartmentId})、设备类型({deviceTypeId})的设置未在批量设置中获取到");
                        continue;
                    }
                    deviceSettingList.Add(GenegrateDeviceSetting(golbalSetting!, depSetting!, depDeviceTypeSetting!, deviceSetting!));
                }
            }
            return deviceSettingList;
        }

        // 生成设备配置
        private CustomSettingDto GenegrateDeviceSetting(CustomSettingDto globalSetting, CustomSettingDto depSetting, CustomSettingDto depDevieTypeSetting, CustomSettingDto deviceSetting)
        {
            var setting = new CustomSettingDto();
            setting.Id = null;
            setting.DepartmentId = deviceSetting.DepartmentId;
            setting.DeviceTypeId = depDevieTypeSetting.DeviceTypeId;
            setting.DeviceId = deviceSetting.DeviceId;

            #region AppointableCount （可预约天数） 
            if (deviceSetting.AppointableCount != null)
            {
                setting.AppointableCount = deviceSetting.AppointableCount;
            }
            else if (depDevieTypeSetting.AppointableCount != null)
            {
                setting.AppointableCount = depDevieTypeSetting.AppointableCount;
            }
            else if (depSetting.AppointableCount != null)
            {
                setting.AppointableCount = depSetting.AppointableCount;
            }
            else if (globalSetting.AppointableCount != null)
            {
                setting.AppointableCount = globalSetting.AppointableCount;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","AppointableCount(可预约天数)"}
                    }
                };
            }
            #endregion

            #region (自动预约可预约天数)
            if (depDevieTypeSetting.AutoAppointableCount != null)
            {
                setting.AutoAppointableCount = depDevieTypeSetting.AutoAppointableCount;
            }
            else if (depSetting.AutoAppointableCount != null)
            {
                setting.AutoAppointableCount = depSetting.AutoAppointableCount;
            }
            else if (globalSetting.AppointableCount != null)
            {
                setting.AutoAppointableCount = globalSetting.AutoAppointableCount;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","AutoAppointableCount(自动预约天数)"}
                    }
                };
            }
            #endregion

            #region Earliest (可提前签到分钟数)
            if (deviceSetting.Earliest != null)
            {
                setting.Earliest = deviceSetting.Earliest;
            }
            else if (depDevieTypeSetting.Earliest != null)
            {
                setting.Earliest = depDevieTypeSetting.Earliest;
            }
            else if (depSetting.Earliest != null)
            {
                setting.Earliest = depSetting.Earliest;
            }
            else if (globalSetting.Earliest != null)
            {
                setting.Earliest = globalSetting.Earliest;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","Earliest(可提前签到分钟数)"}
                    }
                };
            }
            #endregion

            #region CheckInMode (签到模式)
            if (deviceSetting.CheckInMode != null)
            {
                setting.CheckInMode = deviceSetting.CheckInMode;
            }
            else if (depDevieTypeSetting.CheckInMode != null)
            {
                setting.CheckInMode = depDevieTypeSetting.CheckInMode;
            }
            else if (depSetting.CheckInMode != null)
            {
                setting.CheckInMode = depSetting.CheckInMode;
            }
            else if (globalSetting.CheckInMode != null)
            {
                setting.CheckInMode = globalSetting.CheckInMode;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","CheckInMode(签到模式)"}
                    }
                };
            }
            #endregion

            #region LatestAppoint (最迟提前预约时间)
            if (deviceSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = deviceSetting.LatestAppoint;
            }
            else if (depDevieTypeSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = depDevieTypeSetting.LatestAppoint;
            }
            else if (depSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = depSetting.LatestAppoint;
            }
            else if (globalSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = globalSetting.LatestAppoint;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","LatestAppoint(最迟提前预约时间)"}
                    }
                };
            }
            #endregion

            #region UnpaidWillBeCancel （未支付预约自动取消）
            if (deviceSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = deviceSetting.UnpaidWillBeCancel;
            }
            else if (depDevieTypeSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = depDevieTypeSetting.UnpaidWillBeCancel;
            }
            else if (depSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = depSetting.UnpaidWillBeCancel;
            }
            else if (globalSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = globalSetting.UnpaidWillBeCancel;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","UnpaidWillBeCancel(是否自动取消未支付预约)"}
                    }
                };
            }
            #endregion

            #region UnpaidTimeLimit (取消未支付预约时间)
            if (deviceSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = deviceSetting.UnpaidTimeLimit;
            }
            else if (depDevieTypeSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = depDevieTypeSetting.UnpaidTimeLimit;
            }
            else if (depSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = depSetting.UnpaidTimeLimit;
            }
            else if (globalSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = globalSetting.UnpaidTimeLimit;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","UnpaidTimeLimit(是否自动取消未支付预约)"}
                    }
                };
            }
            #endregion

            return setting;
        }

        /// <summary>
        /// 获取科室设备类型设置
        /// </summary>
        public async Task<CustomSettingDto> GetDeviceTypeSetting(Guid depId, Guid deviceTypeId)
        {
            // 获取全局设置 
            var globalSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s => s.Level == SettingLevel.Global);
            if (globalSetting == null)
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingNotFound);
            }

            // 获取科室设置
            var depSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s => s.Level == SettingLevel.Department
                                                                                    && s.DepartmentId == depId
                                                                                    && s.DeviceTypeId == null
                                                                                    && s.DeviceId == null);
            if (depSetting == null)
            {
                depSetting = globalSetting;
            }

            // 科室设备类型设置
            var deviceTypeSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s => s.Level == SettingLevel.DeviceType
                                                                                           && s.DepartmentId == depId
                                                                                           && s.DeviceTypeId == deviceTypeId
                                                                                           && s.DeviceId == null);
            if (deviceTypeSetting == null)
            {
                deviceTypeSetting = depSetting;
            }

            var setting = new CustomSettingDto();
            setting.Id = null;

            #region AppointableCount （可预约天数） 
            if (deviceTypeSetting.AppointableCount != null)
            {
                setting.AppointableCount = deviceTypeSetting.AppointableCount;
            }
            else if (depSetting.AppointableCount != null)
            {
                setting.AppointableCount = depSetting.AppointableCount;
            }
            else if (globalSetting.AppointableCount != null)
            {
                setting.AppointableCount = globalSetting.AppointableCount;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","AppointableCount(可预约天数)"}
                    }
                };
            }
            #endregion

            #region (自动预约可预约天数)
            if (deviceTypeSetting.AutoAppointableCount != null)
            {
                setting.AutoAppointableCount = deviceTypeSetting.AutoAppointableCount;
            }
            else if (depSetting.AutoAppointableCount != null)
            {
                setting.AutoAppointableCount = depSetting.AutoAppointableCount;
            }
            else if (globalSetting.AppointableCount != null)
            {
                setting.AutoAppointableCount = globalSetting.AutoAppointableCount;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","AutoAppointableCount(自动预约天数)"}
                    }
                };
            }
            #endregion

            #region Earliest (可提前签到分钟数)
            if (deviceTypeSetting.Earliest != null)
            {
                setting.Earliest = deviceTypeSetting.Earliest;
            }
            else if (depSetting.Earliest != null)
            {
                setting.Earliest = depSetting.Earliest;
            }
            else if (globalSetting.Earliest != null)
            {
                setting.Earliest = globalSetting.Earliest;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","Earliest(可提前签到分钟数)"}
                    }
                };
            }
            #endregion

            #region CheckInMode (签到模式)
            if (deviceTypeSetting.CheckInMode != null)
            {
                setting.CheckInMode = deviceTypeSetting.CheckInMode;
            }
            else if (depSetting.CheckInMode != null)
            {
                setting.CheckInMode = depSetting.CheckInMode;
            }
            else if (globalSetting.CheckInMode != null)
            {
                setting.CheckInMode = globalSetting.CheckInMode;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","CheckInMode(签到模式)"}
                    }
                };
            }
            #endregion

            #region LatestAppoint (最迟提前预约时间)
           if (deviceTypeSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = deviceTypeSetting.LatestAppoint;
            }
            else if (depSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = depSetting.LatestAppoint;
            }
            else if (globalSetting.LatestAppoint != null)
            {
                setting.LatestAppoint = globalSetting.LatestAppoint;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","LatestAppoint(最迟提前预约时间)"}
                    }
                };
            }
            #endregion

            #region UnpaidWillBeCancel （未支付预约自动取消）
            if (deviceTypeSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = deviceTypeSetting.UnpaidWillBeCancel;
            }
            else if (depSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = depSetting.UnpaidWillBeCancel;
            }
            else if (globalSetting.UnpaidWillBeCancel != null)
            {
                setting.UnpaidWillBeCancel = globalSetting.UnpaidWillBeCancel;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","UnpaidWillBeCancel(是否自动取消未支付预约)"}
                    }
                };
            }
            #endregion

            #region UnpaidTimeLimit (取消未支付预约时间)
            if (deviceTypeSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = deviceTypeSetting.UnpaidTimeLimit;
            }
            else if (depSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = depSetting.UnpaidTimeLimit;
            }
            else if (globalSetting.UnpaidTimeLimit != null)
            {
                setting.UnpaidTimeLimit = globalSetting.UnpaidTimeLimit;
            }
            else
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingAttributeIsNull)
                {
                    Data =
                    {
                        { "attributeName","UnpaidTimeLimit(是否自动取消未支付预约)"}
                    }
                };
            }
            #endregion

            return setting;
        }

        /// <summary>
        /// 获取全局设置
        /// </summary>
        /// <returns></returns>
        public async Task<CustomSettingDto> GetGlobalSetting()
        {
            // 获取全局设置 
            var globalSetting = await _customSettingRepostitory.FirstOrDefaultAsync(s => s.Level == SettingLevel.Global);
            if (globalSetting == null)
            {
                throw new BusinessException(CustomErrorCodes.GlobalSettingNotFound);
            }

            return _mapper.Map<CustomSetting, CustomSettingDto>(globalSetting);
        }
    }
}
